
#include "apue.h"

ssize_t writen(int fd, const void *ptr, size_t n)
{
    ssize_t nwritten;
    size_t nleft = n;

    while (nleft > 0)
    {
        if ((nwritten = write(fd, ptr, nleft)) < 0)
        {
            if (nleft == n)
            {
                return-1;
            }
            else
            {
                break; // error, return amount written so far
            }
        }
        else if (0 == nwritten)
        {
            break;
        }

        nleft -= nwritten;
        ptr   += nwritten;
    }

    return (n - nleft);  // return >= 0
}
